package team.unstudio.unknownrpg_base.loretable;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Nonnull;

import org.bukkit.plugin.java.JavaPlugin;

import com.google.common.base.Strings;

import indi.defoliation.unknownrpg.api.attribute.Attribute;
import indi.defoliation.unknownrpg.api.attribute.NumberAttribute;
import indi.defoliation.unknownrpg.api.config.YamlConfigurer;
import indi.defoliation.unknownrpg.api.util.replace.ReplaceHepler;
import indi.defoliation.unknownrpg.api.util.replace.Replacer;
import indi.defoliation.unknownrpg.api.util.replace.StringReplacer;

public class LoreTableManager {

	private YamlConfigurer config;
	private static ReplaceHepler rh;
	private static DecimalFormat format = new DecimalFormat("#.00");

	public LoreTableManager(JavaPlugin plugin) {
		config = new YamlConfigurer(plugin,"LoreTableConfig.yml");
		rh = new ReplaceHepler();
	}

	public List<String> getLore(BaseLoreTable table,Attribute... att) {
		//TODO 还要删掉那些没有属性的lore
		List<String> list = config.getValue(table.getKey());

		StringBuffer sb = new StringBuffer();

		for(String s:list)
			sb.append(s+"\n");

		String str = replace(sb.toString(),att);

		list.clear();

		for(String s: str.split("[\n]"))
			if(!Strings.isNullOrEmpty(s))
				list.add(s);
		return list;
	}

	private String replace(@Nonnull String str,@Nonnull Attribute... attributes) {
		HashMap<String,Replacer> map = new HashMap<>();
		for(Attribute att : attributes) {
			map.putAll(rh.getMapIfStartWithKey(att.getKeyName()));
		}

		return StringReplacer.replace(str, map, "{", "}");
	}

	public static void putReplacer(Attribute att,String suffix,Replacer r) {
		rh.putReplacer(att.getKeyName()+"."+suffix, r);
	}
	
	public static void putReplacer(Attribute att) {
		rh.putReplacer(att.getKeyName(), ()->att.getDisplayName());
	}

	public static void putReplacer(NumberAttribute<?> numberAttribute) {
		Attribute att = numberAttribute.getAttribute();
		putReplacer(att,"value",()-> getFormat(numberAttribute.get()));
	}

	private static String getFormat(Number number) {
		if(number instanceof Integer)
			return number.toString();
		else if(number instanceof Double)
			return format.format((Double)number);
		else if(number instanceof Float)
			return format.format((Float)number);
		else if(number instanceof Long)
			return number.toString();
		else if(number instanceof Short)
			return number.toString();
		return "";
	}

	public void register(BaseLoreTable table) {
		config.set(table.getKey(), new ArrayList<>());
	}

	public void reload() {
		config.reload();
	}
}
